# -*- coding:utf-8 -*-
import os, sys
import csv as CSV
import inspect
import configparser
from Util.log import FrameLog
import numpy as np


log = FrameLog().log()

NULL_LIST = [np.nan, np.NaN, " ", "", None, "nan", "NaN", "None", "null", []]


def is_null(tgt):
    """
    查看输入的是不是null
    :param tgt: 输入的string或者unicode
    :return: boolean
    """
    if tgt not in NULL_LIST:
        return False
    else:
        return True


def mkdir(path):
    """ 递归创建目录 """
    path = path.strip()  # 去除首位空格
    path = path.rstrip("//")  # 去除尾部 / 符号
    is_exists = os.path.exists(path)  # 判断路径是否存在(True存在，False不存在)
    # 判断结果
    if not is_exists:
        os.makedirs(path)
        log.info(path + ' 目录创建成功')
        return True
    else:
        log.info(path + ' 目录已存在')
        return False


def get_locator_data(pro_name, csv_file):
    """
        获取元素定位数据
        { "属性名称": [ "定位方式", "定位值", "高亮" ] }
    """
    locator_data = {}
    file = os.path.join(project_path(), 'Project', pro_name, 'page_locator', csv_file)
    with open(file, 'r', encoding='utf-8') as f:
        itor = CSV.reader(f)
        itor.__next__()  # 遍历下一个（从第二行开始读取）
        for i in itor:
            locator_data[i[1]] = i[2:]
        return locator_data


def get_ini_data(pro_name, ini_test_file):
    """
        获取测试数据
            返回的 ini_config 对象 如何取值
            value = ini_config.get(section=title, option=key)
            '上海' = ini_config.get(section="test_qunar_case_01", option="from")
    """
    ini_config = configparser.ConfigParser()
    ini_config.read(os.path.join(project_path(), 'Project', pro_name, 'test_data', ini_test_file))
    return ini_config


def get_test_url(pro_name):
    """ 获取测试地址 """
    return get_ini_data(pro_name, 'test_url.ini')


def get_case_name(pro_name, test_method_name):
    """
        获取 用例名称（ 从ini文件中 ）
    :param pro_name:
    :param test_method_name:
    :return:
    """
    case_name = None
    # 获取指定项目'test_data'目录下的所有文件
    test_data_dir = os.path.join(project_path(), 'Project', pro_name, 'test_data')
    file_list = os.listdir(test_data_dir)
    for file in file_list:
        # 判断是否为文件类型，且以.ini结尾
        if os.path.isfile(f'{test_data_dir}/{file}') and file.endswith(".ini"):
            try:
                case_name = get_ini_data(pro_name, file).get(section=test_method_name, option="case_name")
                break
            except Exception:
                continue
    return case_name


def get_func_name():
    """ 获取正在运行函数的名称 """
    return inspect.stack()[1][3]


def project_path():
    """ 获取项目路径 """
    return os.path.split(os.path.realpath(__file__))[0].split('/Util')[0]  # 将当前 Util 目录作为分隔


def get_current_function_name(class_instance):
    """ 获取当前的'类名/方法名/'(提供截屏路径使用) """
    return class_instance.__class__.__name__ + "/" + inspect.stack()[1][3] + "/"


if __name__ == '__main__':
    # 获取项目根目录
    # 获取当前文件的上级目录
    # data_dir = os.path.abspath(os.path.dirname(os.getcwd()))
    # print(data_dir)

    # test_data = data_dir + "/Project/pro_demo_1/test_data/train_data.csv"
    # test_data = project_path() + "/Project/pro_demo_1/test_data/train_data.csv"
    # csv_data = csv(file=test_data, type="case")
    # print(csv_data)
    # test_data = get_test_data(csv_data, "params")
    # print(test_data)
    # print(test_data["test_ctrip_case_01"]["leave"])
    # test_assert = get_test_data(csv_data, "assert")
    # print(test_assert)
    # print()

    # page_data = project_path() + "/Project/pro_demo_1/page_locator/search_page.csv"
    # csv_data = csv(file=page_data, type="page")
    # print(csv_data)

    # test_case_path = project_path() + "/Api/templates/element_demo.html"
    # print(test_case_path)

    case_name = get_case_name(pro_name="pro_demo_1", test_method_name="test_01")
    print(case_name)
